#! /bin/bash

GOSRC=$GOPATH/src
abs=`pwd`


. $GOSRC/xp/script/env.sh


mainFile="${GOSRC}/xp/${1}/main.go"
toolFile="${GOSRC}/xp/${1}/tool.go"
confFile="${GOSRC}/xp/conf.cfg"
publicDir="${GOSRC}/xp/${1}/public"
tplDir="${GOSRC}/xp/${1}/public/tpl"
errNotFoundPage="${GOSRC}/xp/${1}/public/tpl/404.html"
errPanicPage="${GOSRC}/xp/${1}/public/tpl/500.html"

mkdir $GOSRC/xp/$1

# Create public files
mkdir $publicDir
mkdir $tplDir


# write prot to conf.cfg
cat >> $confFile << EOF
$1 = $2
EOF

# create main file
touch "$mainFile"
cat > $mainFile << EOF
package main

import (
	"bytes"

	"xp/lib/errors"
	"xp/lib/etc"
	"xp/lib/httpx"
	"xp/lib/log"
	"xp/lib/mux"
	"xp/lib/mux/behavior"
	"xp/lib/mux/web"
	"xp/lib/signal"

	http "github.com/valyala/fasthttp"
)

//go:generate xp_tools_gen -pkg .

func main() {
	server, err := httpx.ListenAndServe(etc.Int("http_port", "$1"), router.Handler)
	if err != nil {
		log.Fatal("err", err.Error())
	}
	signal.ListenAndServe(server)
}

var (
	router = mux.New("/$1/", func(r *mux.Router) {
		errPages := web.ErrorPage(map[int]string{
			404: "./public/tpl/404.html",
			500: "./public/tpl/500.html",
		})
		r.NotFound = notFoundHandler
		r.Use(behavior.Recorder, mux.NewPanicRecover(panicHandler), mux.Context, errPages, web.NamedSession("__s_$1"))
	})
)

func initGenRouter() *mux.Router {
	clone := router.Clone("/$1/")
	return clone
}

func init() {
	router.Deck("/", func(r *mux.Router) {
		r.UseOnly(mux.NewPanicRecover(nil))
		r.ServeFiles("/public/*filepath", "./public")
	})

	web.LoadTemplate("./public/tpl", ".html")
}

var (
	tplPath = []byte(\`/public/tpl\`)
)

func ignoreTpl(next mux.Handler) mux.Handler {
	return func(ctx *mux.Ctx) {
		if bytes.HasPrefix(ctx.Path(), tplPath) {
			ctx.Status(403, []byte(\`request to tpl dir is forbiddened\`))
			return
		}

		// chain up...
		next(ctx)
	}
}

func notFoundHandler(ctx *http.RequestCtx) {
	ctx.Response.Header.Set("Cache-Control", "no-cache, no-store, must-revalidate")
	http.ServeFileUncompressed(ctx, "./public/tpl/404.html")
}

func panicHandler(ctx *mux.Ctx) {
	if ctx.IsGet() && !web.IsAjax(ctx) {
		ctx.Response.Header.Set("Cache-Control", "no-cache, no-store, must-revalidate")
		http.ServeFileUncompressed(ctx.RequestCtx, "./public/tpl/500.html")
	} else {
		ctx.Error(errors.CodeInternal)
	}
}
EOF

# Create 404 page
touch "$errNotFoundPage"
cat > $errNotFoundPage << EOF
<!DOCTYPE html>
<html>

<head>
    <meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport">
    <title>您探索了未知区域! (404)</title>
    <style>
    body {
        color: #666;
        text-align: center;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        margin: auto;
        font-size: 14px;
    }
    
    h1 {
        font-size: 56px;
        line-height: 100px;
        font-weight: normal;
        color: #456;
    }
    
    h2 {
        font-size: 24px;
        color: #666;
        line-height: 1.5em;
    }
    
    h3 {
        color: #456;
        font-size: 20px;
        font-weight: normal;
        line-height: 28px;
    }
    
    hr {
        max-width: 800px;
        margin: 18px auto;
        border: 0;
        border-top: 1px solid #EEE;
        border-bottom: 1px solid white;
    }
    
    img {
        max-width: 40vw;
    }
    
    .container {
        margin: auto 20px;
    }
    </style>
</head>

<body>
    <h1>404</h1>
    <div class="container">
        <h3>您探索了未知区域</h3>
        <hr />
        <p>请您返回到<a href="">主页</a>。</p>
    </div>
</body>

</html>
EOF

# Create 500 page
touch "$errPanicPage"
cat > $errPanicPage << EOF
<!DOCTYPE html>
<html>

<head>
    <meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport">
    <title>Oops! (500)</title>
    <style>
    body {
        color: #666;
        text-align: center;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        margin: auto;
        font-size: 14px;
    }
    
    h1 {
        font-size: 56px;
        line-height: 100px;
        font-weight: normal;
        color: #456;
    }
    
    h2 {
        font-size: 24px;
        color: #666;
        line-height: 1.5em;
    }
    
    h3 {
        color: #456;
        font-size: 20px;
        font-weight: normal;
        line-height: 28px;
    }
    
    hr {
        max-width: 800px;
        margin: 18px auto;
        border: 0;
        border-top: 1px solid #EEE;
        border-bottom: 1px solid white;
    }
    
    img {
        max-width: 40vw;
    }
    
    .container {
        margin: auto 20px;
    }
    </style>
</head>

<body>
    <h1>500</h1>
    <div class="container">
        <h3>好像出了点问题</h3>
        <hr />
        <p>请您稍后访问。</p>
    </div>
</body>

</html>
EOF

touch "$toolFile"
cat > $toolFile << EOF
package main

import (
	"xp/lib/mux"
	"xp/lib/mux/web"
)

func xTemplate(ctx *mux.Ctx, name string, data map[string]interface{}) {
	if data == nil {
		data = make(map[string]interface{})
	}
	web.Template(ctx, name, data)
}
EOF

